<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button icon="el-icon-edit" type="primary" @click="showAddDialog()"
          >新增</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-input v-model="search" placeholder="输入学期名">
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="
        list
          .filter(
            (data) =>
              !search ||
              data.semesterName.toLowerCase().includes(search.toLowerCase())
          )
          .slice((currentPage - 1) * pagesize, currentPage * pagesize)
      "
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="40px">
        <template slot-scope="scope">
          {{ scope.$index + 1 + (currentPage - 1) * pagesize }}
        </template>
      </el-table-column>
      <el-table-column label="学期名" prop="semesterName" align="center">
        <template slot-scope="scope">
          {{ scope.row.semesterName }}
        </template>
      </el-table-column>
      <el-table-column
        label="学期总周数"
        prop="semesterWeeksSum"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.semesterWeeksSum }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="学期开始日"
        prop="semesterStartDate"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.semesterStartDate }}
        </template>
      </el-table-column>
      <el-table-column label="学期结束日" prop="semesterEndDate" align="center">
        <template slot-scope="scope">
          {{ scope.row.semesterEndDate }}
        </template>
      </el-table-column>
      <el-table-column label="排课状态" prop="semesterStatus" align="center">
        <template slot-scope="scope">
          {{ scope.row.semesterStatus == 0 ? "未排课" : "已排课" }}
        </template>
      </el-table-column>

      <el-table-column align="center" prop="action" label="操作">
        <template slot-scope="scope">
          <span>
            <el-button icon="el-icon-edit" @click="showUpdateDialog(scope.row)"
              >更新</el-button
            >
            <el-button icon="el-icon-delete" @click="deleted(scope.row)"
              >删除</el-button
            >
          </span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 1rem; margin-left: 0.4rem"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 7, 10]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="
        list.filter(
          (data) =>
            !search ||
            data.semesterName.toLowerCase().includes(search.toLowerCase())
        ).length
      "
    >
    </el-pagination>

    <!-- 弹窗 -->
    <el-dialog title="学期" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="学期名">
          <el-input v-model="form.semesterName"></el-input>
        </el-form-item>

        <el-form-item label="学期总周数">
          <el-input-number
            v-model="form.semesterWeeksSum"
            :disabled="form.semesterStatus == 1"
            controls-position="right"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="开始日期">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.semesterStartDate"
              style="width: 100%"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{
            form.id == null ? "添加" : "更新"
          }}</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        2: "success",
        0: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      list: null,
      listLoading: true,
      search: "",
      currentPage: 1,
      currentIndex: "",
      pagesize: 5,

      // 新增/更新 的弹窗
      dialogFormVisible: false,
      form: {
        id: null,
        semesterName: "",
        semesterWeeksSum: 0,
        semesterStartDate: "",
        semesterStatus: 0,
      },
      pickerOptions: {
        disabledDate(time) {
          // 限制只能选周一
          const date = new Date(time);
          return date.getDay() != 1;
        },
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    getList() {
      this.listLoading = true;
      this.$axios
        .get("/semester/getList", {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.list = res.data.data;
          this.listLoading = false;
        });
    },
    onSubmit() {
      this.form.id == null ? this.add() : this.update();
      this.dialogFormVisible = false;
    },
    showAddDialog() {
      this.form.id = null;
      this.form.semesterName = "";
      this.form.semesterWeeksSum = 0;
      this.form.semesterStartDate = "";
      this.form.semesterStatus = 0;
      this.dialogFormVisible = true;
    },
    showUpdateDialog(semester) {
      this.form.id = semester.id;
      this.form.semesterName = semester.semesterName;
      this.form.semesterWeeksSum = semester.semesterWeeksSum;
      this.form.semesterStartDate = semester.semesterStartDate;
      this.form.semesterStatus = semester.semesterStatus;
      this.dialogFormVisible = true;
      // 未排课可修改全部
      // 已排课就不能修改semesterWeeksSum
    },
    add() {
      let form = this.form;
      this.$axios
        .post("/semester", form, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.$message({
            message: "添加成功!",
            type: "success",
          });
          this.getList();
        });
    },
    update() {
      let form = this.form;
      this.$axios
        .put("/semester", form, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.$message({
            message: "更新成功!",
            type: "success",
          });
          this.getList();
        });
    },
    deleted(semester) {
      this.$confirm(
        "将会删除学期" + semester.semesterName + "关联的所有课表，是否继续？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 在Axios中，DELETE请求通常不接受第二个参数作为请求体
          this.$axios
            .delete("/semester/" + semester.id, {
              headers: {
                Authorization: localStorage.getItem("token"),
              },
            })
            .then((res) => {
              this.$message({
                message: "删除成功!",
                type: "success",
              });
              this.getList();
            });
        })
        .catch(() => {
          this.$message({
            message: "操作已取消",
            type: "info",
          });
        });
    },
  },
};
</script>
